package com.example.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.reggie.common.R;
import com.example.reggie.entity.User;
import com.example.reggie.service.UserService;
import com.example.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 发送短信
     * redis缓存验证码思路:
     *   1.缓存短信验证码，将生成的验证码保存Redis中，以字符串形式存储吗 phone - code ，设置时效为5min
     *   2.登录之后删除redis中保存的 phone -code 数据
     * @param user
     * @param session
     * @return
     */
    @RequestMapping("/sendMsg")
    public R<String> code(@RequestBody User user, HttpSession session){

        String phone = user.getPhone();
        //生成随机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        log.info("生成验证码{}",code);

        //将生成的验证码保存Session中
//        session.setAttribute(phone,code);


        //将生成的验证码保存到Redis中，设置有效时间为5min
        redisTemplate.opsForValue().set(phone,code,5L, TimeUnit.MINUTES);

        return R.success("手机发送验证码成功");

    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){

        log.info("");

        String phone = map.get("phone").toString();

        String code = map.get("code").toString();
//        //从Session中获取保存的验证码
//        Object codeInSession = session.getAttribute(phone);

        //从Redis中获取验证码
        Object object = redisTemplate.opsForValue().get(phone);

        if(object != null && object.equals(code)){

            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

            lambdaQueryWrapper.eq(User::getPhone,phone);

            User user = userService.getOne(lambdaQueryWrapper);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //登录成功后删除Rddis中的code
            redisTemplate.delete(phone);

            return R.success(user);
        }


        return  R.error("登录失败");
    }
}
